﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System.Diagnostics;
using System.Net.Http;

namespace MiddleCollection
{
    /// <summary>
    /// 计算接口执行时间中间件
    /// </summary>
    public class CalculateExecutionTimeMiddleware
    {
        private readonly RequestDelegate _next;//下一个中间件
        private readonly ILogger<CalculateExecutionTimeMiddleware> _logger;
      
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="next"></param>
        /// <param name="logger"></param>
        public CalculateExecutionTimeMiddleware(RequestDelegate next, ILogger<CalculateExecutionTimeMiddleware> logger)
        {
            _next = next;
            _logger = logger;
        }
        /// <summary>
        /// 执行中间件
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task Invoke(HttpContext context)
        {
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();//在下一个中间价处理前，启动计时器 
            _logger.LogInformation("访问者 Ip:" + context.Connection.RemoteIpAddress.ToString());

            await _next.Invoke(context);

            stopwatch.Stop();//所有的中间件处理完后，停止秒表。
            _logger.LogInformation($@"接口路径 {context.Request.Path} 耗时{stopwatch.ElapsedMilliseconds}ms");
        }
    }
}
